<template>
  <!-- <div>
    <h1 class="basic_info">基本信息</h1>
    <div class="clear"></div>

    <el-form
        :model="visaProductForm"
        :rules="visaProductRules"
        ref="basicInfoForm"
        class="basicInfoForm"
        label-position="left"
    >
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="国家" prop="countryId" label-width="50px">
            <el-select v-model="visaProductForm.countryId" placeholder="请选择国家">
              <el-option
                  v-for="item in countryOptions"
                  :key="item.id"
                  :label="item.countryName"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="大洲" prop="continent" label-width="50px">
            <el-select v-model="visaProductForm.continent" placeholder="请选择大洲">
              <el-option
                  v-for="item in continentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="领区" prop="regionId" label-width="50px">
            <el-select v-model="visaProductForm.regionId" placeholder="请选择领区">
              <el-option
                  v-for="item in regionOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="签证类型" prop="visaTypeId" label-width="80px">
            <el-select v-model="visaProductForm.visaTypeId" placeholder="请选择签证类型" class="long-select">
              <el-option
                  v-for="item in visaTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name" label-width="80px">
            <el-input
                v-model="visaProductForm.name"
                placeholder="请输入签证名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="办理时长" prop="transactTime" label-width="80px">
            <el-input
                v-model="visaProductForm.transactTime"
                placeholder="请输入办理时长"
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="产品价格" prop="price" label-width="80px">
            <el-input
                v-model="visaProductForm.price"
                placeholder="请输入价格"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="有效期限" prop="expireDate" label-width="80px">
            <el-input
                v-model="visaProductForm.expireDate"
                placeholder="请输入有效期限"
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="最长停留" prop="maxStay" label-width="80px">
            <el-input
                v-model="visaProductForm.maxStay"
                placeholder="请输入最长停留时间"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="入境次数" prop="entryNumber" label-width="80px">
            <el-input
                v-model="visaProductForm.entryNumber"
                placeholder="请输入入境次数"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h1 class="template_setting">模板配置</h1>
    <div class="clear"></div>

    <el-form
        :model="visaProductForm"
        class="basicInfoForm"
        label-position="left"
        v-if="applicantGroupOptions && applicantGroupOptions.length > 0"
    >
      <el-row :gutter="5" v-for="(group, index) in applicantGroupOptions" :key="group.id" v-if="index % 2 === 0">
        <el-col :span="12" v-if="applicantGroupOptions[index]">
          <el-form-item :label="applicantGroupOptions[index].name" label-width="100px">
            <el-select v-model="selectedTemplates[applicantGroupOptions[index].id]" placeholder="选择模板"
                       class="template_select">
              <el-option
                  v-for="template in applicantGroupOptions[index].templates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="applicantGroupOptions[index + 1]">
          <el-form-item :label="applicantGroupOptions[index + 1].name" label-width="100px">
            <el-select v-model="selectedTemplates[applicantGroupOptions[index + 1].id]" placeholder="选择模板"
                       class="template_select">
              <el-option
                  v-for="template in applicantGroupOptions[index + 1].templates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h1 class="other_setting">其他设置</h1>
    <div class="clear"></div>

    <el-form
        :model="visaProductForm"
        class="basicInfoForm"
        label-position="left">
      <el-form-item label="热门产品" label-width="80px">
        <el-checkbox v-model="visaProductForm.isHot" true-label="1" false-label="0" class="isHot">显示</el-checkbox>
      </el-form-item>
      <el-form-item label="产品状态" label-width="80px">
        <el-checkbox v-model="visaProductForm.isShow" true-label="1" false-label="0" class="isShow">上线</el-checkbox>
      </el-form-item>
    </el-form>


    <el-button round class="submit" @click="submitForm">确认</el-button>
    <el-button round class="submit">取消</el-button>

  </div> -->
</template>

<script>
import axios from "@/utils/request";

export default {
  data() {
    return {
      visaProductId: this.$route.params.id,
      visaProductForm: {
        id: '', //  要包含ID
        countryId: '',
        continent: '',
        regionId: '',
        visaTypeId: '',
        name: '',
        transactTime: '',
        price: '',
        expireDate: '',
        maxStay: '',
        entryNumber: '',
        isHot: 0,
        isShow: 0,
      },
      visaProductRules: {
        countryId: [{ required: true, message: '请选择国家', trigger: 'change' }],
        continent: [{ required: true, message: '请选择大洲', trigger: 'change' }],
        regionId: [{ required: true, message: '请选择领区', trigger: 'change' }],
        visaTypeId: [{ required: true, message: '请选择签证类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入签证名称', trigger: 'change' }],
        transactTime: [{ required: true, message: '请输入办理时长', trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'change' }],
        expireDate: [{ required: true, message: '请输入有效期限', trigger: 'change' }],
        maxStay: [{ required: true, message: '请输入最长停留时间', trigger: 'change' }],
        entryNumber: [{ required: true, message: '请输入入境次数', trigger: 'change' }],
      },
      countryOptions: [],
      continentOptions: [
        { value: '亚洲', label: '亚洲' },
        { value: '欧洲', label: '欧洲' },
        { value: '北美洲', label: '北美洲' },
        { value: '南美洲', label: '南美洲' },
        { value: '非洲', label: '非洲' },
        { value: '大洋洲', label: '大洋洲' },
        { value: '南极洲', label: '南极洲' },
      ],
      regionOptions: [],
      visaTypeOptions: [],
      applicantGroupOptions: [],  //用于存放人群list
      selectedTemplates: {}, // 用于存储每个适用人群选择的模板ID
    }
  },
  mounted() {
    this.fetchOptions();
    this.fetchApplicantGroups();
    this.fetchVisaProduct(); // 获取签证产品详情
  },
  methods: {
    async fetchOptions() {
      try {
        const countryRes = await axios.get("/admin/template/countries");
        this.countryOptions = countryRes.data;

        const visaTypeRes = await axios.get("/admin/template/visa-types");
        this.visaTypeOptions = visaTypeRes.data;

        const regionRes = await axios.get("/admin/template/regions");
        this.regionOptions = regionRes.data;
      } catch (error) {
        this.$message.error("加载选项失败");
      }
    },
    async fetchApplicantGroups() {
      try {
        const applicantGroupRes = await axios.get("/admin/template/applicant-groups");
        console.log("applicantGroupRes.data", applicantGroupRes.data);
        this.applicantGroupOptions = applicantGroupRes.data.map(group => {
          // 为每个适用人群添加一个 templates 属性，并初始化为空数组
          group.templates = [];
          this.fetchTemplatesForGroup(group.id);  // 获取和用户组关联的模板数据
          return group;
        });
      } catch (error) {
        this.$message.error("加载适用人群列表失败");
      }
    },
    async fetchTemplatesForGroup(applicantGroupId) {
      try {
        const templateRes = await axios.get(`/admin/template/applicant-group/${applicantGroupId}/templates`);
        // 找到当前的用户组，并把请求到的模板数据赋值给templates
        if (templateRes.code === 1) {
          const group = this.applicantGroupOptions.find(group => group.id === applicantGroupId);
          if (group) {
            group.templates = templateRes.data;
          }

        } else {
          this.$message.error("加载适用人群列表失败");
        }
      } catch (error) {
        this.$message.error("加载适用人群列表失败");
      }
    },

    async fetchVisaProduct() {
      try {
        const res = await axios.get(`/admin/visaProduct/${this.visaProductId}`);
        if (res.code === 1) {
          // 将后端返回的数据填充到 visaProductForm 中
          Object.assign(this.visaProductForm, res.data);

          // 将 isHot 和 isShow 转换为布尔值
          this.visaProductForm.isHot = res.data.isHot === 1;
          this.visaProductForm.isShow = res.data.isShow === 1;

          console.log("this.applicantGroupOptions (before template logic)", this.applicantGroupOptions);

          // 回显模板选择
          if (res.data.templateIdsList && res.data.templateIdsList.length > 0) {
            this.selectedTemplates = {};
            const templateIdsList = res.data.templateIdsList.map(id => parseInt(id)); // 确保是数字类型
            console.log("templateIdsList", templateIdsList);

            this.applicantGroupOptions.forEach(group => {
              group.templates.forEach(template => {
                console.log("group:", group.templates);
                if (templateIdsList.includes(template.id)) {
                  this.$set(this.selectedTemplates, String(group.id), template.id);
                }
              });
            });

            console.log("selectedTemplates", this.selectedTemplates);
          }

          this.$forceUpdate(); // 强制更新组件
        } else {
          this.$message.error("加载签证产品详情失败");
        }
      } catch (error) {
        this.$message.error("加载签证产品详情失败");
      }
    },

    async submitForm() {
      try {
        // 1. 整理模板ID
        const templateIds = Object.values(this.selectedTemplates).filter(id => id !== null && id !== undefined);

        // 2. 构造请求体
        const requestBody = {
          id: this.visaProductForm.id,
          countryId: this.visaProductForm.countryId,
          continent: this.visaProductForm.continent,
          regionId: this.visaProductForm.regionId,
          visaTypeId: this.visaProductForm.visaTypeId,
          name: this.visaProductForm.name,
          transactTime: this.visaProductForm.transactTime,
          price: this.visaProductForm.price,
          expireDate: this.visaProductForm.expireDate,
          maxStay: this.visaProductForm.maxStay,
          entryNumber: this.visaProductForm.entryNumber,
          isHot: this.visaProductForm.isHot ? 1 : 0, // 提交前转为 0 或 1
          isShow: this.visaProductForm.isShow ? 1 : 0, // 提交前转为 0 或 1
          templateIds: templateIds
        };

        // 3. 发送PUT请求
        const res = await axios.put('/admin/visaProduct', requestBody);

        if (res.code === 1) {
          this.$message.success("签证产品更新成功");
          this.$router.push('/main/visaProduct'); // 更新成功后跳转到列表页
        } else {
          this.$message.error("签证产品更新失败");
        }

      } catch (error) {
        this.$message.error("签证产品更新失败");
      }
    }

  },

}
</script>

<style scoped>
.basic_info {
  float: left;
}

.clear {
  clear: both;
}

.basicInfoForm {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 15px;
}

.long-select {
  width: 560px;
}

.template_select {
  width: 500px;
}

.template_setting {
  float: left;
}

.other_setting {
  float: left;
}

.isHot {
  float: left;
}

.isShow {
  float: left;
}

.submit {
  margin-top: 50px;
}
</style>